<?php

namespace App\Services;

use App\Exceptions\BusinessException;
use App\Models\BaseModel;
use App\Models\User;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;

class UserService extends BaseService
{
    /**
     * 查询或创建
     * @param array $params
     * @return Builder|Model|object|null
     * @throws BusinessException
     */
    public function firstOrCreate(array $params)
    {
        // 查询用户
        $user = User::query()->where('openid', $params['openid'])->first();
        if ($user) {
            // 登录
            if ($user->status != BaseModel::STATUS_ENABLE) {
                $this->throwBusinessException('用户有异常，请联系客服');
            }
        } else {
            // 注册
            $params['user_sn'] = User::getSn();
            $params['status'] = BaseModel::STATUS_ENABLE;
            $params['created_at'] = date('Y-m-d H:i:s');
            $user = User::create($params);
        }

        return $user;
    }

    /**
     * 编辑信息
     * @param $uid
     * @param $name
     * @param $avatar
     * @param $sex
     * @param $birth
     * @return void
     * @throws BusinessException
     */
    public function editInfo($uid, $name, $avatar, $sex, $birth)
    {
        // 查询用户
        $user = User::query()->where('id', $uid)->first();
        if (!$user) {
            $this->throwBusinessException('用户未注册');
        }

        $user->name = $name;
        $user->avatar = $avatar;
        $user->sex = $sex;
        $user->birth = $birth;
        $user->updated_at = date('Y-m-d H:i:s');
        $user->save();
    }

    /**
     * 编辑手机号
     * @param $uid
     * @param $country
     * @param $phone
     * @return void
     * @throws BusinessException
     */
    public function editPhone($uid, $country, $phone)
    {
        // 查询用户
        $user = User::query()->where('id', $uid)->first();
        if (!$user) {
            $this->throwBusinessException('用户未注册');
        }

        $user->country = $country;
        $user->phone = $phone;
        $user->updated_at = date('Y-m-d H:i:s');
        $user->save();
    }

    /**
     * 用户信息
     * @param $uid
     * @return array|mixed[]
     * @throws BusinessException
     */
    public function info($uid)
    {
        // 查询用户
        $user = User::query()->where('id', $uid)->first(['user_sn', 'name', 'avatar', 'sex', 'birth', 'phone', 'email', 'country', 'is_worker']);
        if (!$user) {
            $this->throwBusinessException('用户未注册');
        }
        $user = $user->toArray();
        $user['avatar'] = storage($user['avatar']);
        return $user;
    }
}
